package de.revdev.llt.bean.facade;

import de.revdev.llt.bean.entities.Category;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;

/**
 *
 * @author f.lindermaier
 */
@Stateless
public class CategoryFacade extends AbstractFacade<Category> {

    @PersistenceContext(unitName = "LetsLearnTogetherPU")
    private EntityManager em;

    @Override
    public EntityManager getEntityManager() {
        return em;
    }

    public CategoryFacade() {
        super(Category.class);
    }

    public List<Category> findAllRootCategories() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Category> cq = cb.createQuery(Category.class);
        Root<Category> r = cq.from(Category.class);
        cq.select(r);
        ParameterExpression<Category> p = cb.parameter(Category.class);
        cq.where(cb.isNull(r.get("overCategory")));
        return (List<Category>) em.createQuery(cq).setParameter(p, null).getResultList();
    }

    public List<Category> findUnderCategories(Category category) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Category> cq = cb.createQuery(Category.class);
        Root<Category> r = cq.from(Category.class);
        cq.select(r);
        ParameterExpression<Category> p = cb.parameter(Category.class);
        cq.where(cb.equal(r.get("overCategory"), p));
        return (List<Category>) em.createQuery(cq).setParameter(p, category).getResultList();
    }
}
